<?php
class MiluckydrawAction extends Action{
	public function _initialize(){

		$this->retVal = Session::init();
		if (!$this->retVal) {
			Output::instance()->resultCode(code_access_denied);
			exit;
		}
		$cid = Session::$user["customerId"];
		Session::switchCustomer(0);
		$this->luckydraw_item_db = D('MiluckydrawItem');
		$this->miactivity_partake_db = D('miactivity_partake');
		$this->miluckydraw_record_db = D('miluckydraw_record');

		$this->cid = $cid;
		Session::switchCustomer($cid);
	}
	public function get_item_list($activityId,$returnJson = true){
		
		$map = $result = array();
		$map['cid'] = $this->cid;
		$map['deleted'] = 0 ;
		$map['activityId'] = $activityId;
		$item_list = $this->luckydraw_item_db->where($map)->order('id asc')->select();
		if(!$item_list){
			$result['code'] = 0;
			$result['info'] = '暂无数据';
			$item_list = false;
			$result['item_list'] = $item_list;

		}else{
			$result['code'] = 1;
			$result['item_list'] = $item_list;
		}
		if($returnJson == true){
			Output::instance()->object($result);
		}else{
			return $item_list;
		}
		
	}
	public function item_update(){
		
		$result = array();
		// $_POST = $_GET;
		// IS_POST = 1;
		if(IS_POST){
			$deleted = $_POST['deleted'];
			if($deleted == 1){
				Session::switchCustomer(0);
				$update_result = M('MiluckydrawItem')->where('id='.$_POST['id'])->setField('deleted',1);
				if($update_result){
					$result['code'] = 1;
					$result['info'] = "删除成功";
				}else{
					$result['code'] = 0;
					$result['info'] = "删除失败";
				}
			}else{
				$map = array();
				$map['cid'] = $this->cid;
				$map['title'] = $_POST['title'];
				$map['id'] = array('neq',$_POST['id']);
				$map['activityId'] = $_POST['activityId'];
			// $map['deleted'] = 0;

				$count = $this->luckydraw_item_db->where($map)->count();
				if($count > 0){
					$result['code'] = 0;
					$result['info'] = '奖项不能重名';
				}else{
					$_POST['cid'] = $this->cid;
					$result_update = $this->luckydraw_item_db->update();

					if ($result_update) {
						$result['code'] = 1;
						$result['id'] = $result_update;
					} else {
						$result['code'] = 0;
						$error = $this->luckydraw_item_db->getError();
						$result['info'] = $error?$error:"发生未知错误";
					}
				}

			}
			
		}else{
			$result['code'] = 0;
			$result['info'] = '请使用post方式';
		}
		

		
		Output::instance()->object($result);
	}
   //活动基础统计头部数据
	public function getSummary($activity_id,$returnJson=true){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$cid = Session::$user["customerId"];
		Session::switchCustomer(0);
		$miactivity_partake_db = M('miactivity_partake');
		$miactivity_visit_db = M('miactivity_visit');

		$visit_count  = 0;
		$partake_count = 0;
		$partake_id = 0;
		$photo_count = 0;
		$channel_data = array();
		$date_data = array();



		$sql = 'select count(*) as visit_count from (SELECT  userId  FROM `'.C('DB_PREFIX').'miactivity_visit` WHERE ( `cid` = '.$cid.' ) AND ( `activityId` = '.$activity_id.' ) AND ( `deleted` = 0 ) GROUP BY userId ) t ;';
		$visit_count_search = M()->query($sql);

		$visit_count = $visit_count_search[0]['visit_count'];

		$sql = 'select count(*) as partake_count from (SELECT  userId  FROM `'.C('DB_PREFIX').'miactivity_partake` WHERE ( `cid` = '.$cid.' ) AND ( `activityId` = '.$activity_id.' ) AND ( `deleted` = 0 ) GROUP BY userId ) t ;';
		$partake_count_search = M()->query($sql);
		$partake_count = $partake_count_search[0]['partake_count'];


		$sql = 'select count(*) as winners_count   FROM `'.C('DB_PREFIX').'miluckydraw_record` WHERE ( `cid` = '.$cid.' ) AND ( `activityId` = '.$activity_id.' ) AND (item_type <> 4 )  ;';
		$winners_count_search = M()->query($sql);
		$winners_count = $winners_count_search[0]['winners_count'];

		$activityname = M('miactivity')->where('id='.$activity_id)->getField('activityname');
		$summary_data = array();
		$summary_data['partake_count'] = $partake_count;
		$summary_data['winners_count'] = $winners_count;
		$summary_data['visit_count'] = $visit_count;

		$summary_data['activityname'] = $activityname;
		if($summary_data){
			Session::switchCustomer($cid);
			if($returnJson==true){
				Output::instance()->object($summary_data);
			}else{
				return $summary_data;
			}

		}else{
			Output::instance()->resultCode();
		}

	}

	public function deal_prize($record_id,$prize_status){
		$result = $map = array();
		$result['code'] = 0;
		$map['id'] = $record_id;
        $update_result = $this->miluckydraw_record_db->where($map)->setField('prize_status',$prize_status);
        if($update_result){
        	$result['code'] = 1;
        	$result['info'] = '状态修改成功';
        }else{
            $result['info'] = '状态修改失败';
        }

        Output::instance()->object($result);
	}
	public function getDateChannelSummary($activity_id,$type='channel',$start=0,$limit=10,$returnJson=true){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$cid = Session::$user["customerId"];
		Session::switchCustomer(0);
		$miluckydraw_record_db = M('miluckydraw_record');
		$miactivity_visit_db = M('miactivity_visit');

		$channel_data = array();
		$date_data  = array();
		$summary_data =  array();
		$map = $visit_map = array();
		$map['cid'] = $cid;
		$map['activityId'] = $activity_id;
		$channel_map = array();
		$channel_map['cid'] = $cid;
		$channel_map['deleted'] = 0;
		switch ($type) {
			case 'channel':
			$miactivity_channel_db = M('miactivity_channel');
			$channel_list = $miactivity_channel_db->where($channel_map)->cache(true)->getField('id,name');
			if($returnJson==true){

				$channel_data = $miluckydraw_record_db
				->field('count(*) as partake_count,channelId')
				->where($map)
				->group('channelId')
				->order('channelId asc')
				->limit($start,$limit)
				->select();

				$sql = 'select count(*) as count from (SELECT  channelId  FROM `'.C('DB_PREFIX').'miluckydraw_record` WHERE ( `cid` = '.$cid.' ) AND ( `activityId` = '.$activity_id.' )  GROUP BY channelId ) t ;';
				$count_search = M()->query($sql);
				$count = $count_search[0]['count'];
                // echo $sql;
                // echo 'count='.$count.'<br/>';


			}else{
				$channel_data = $miluckydraw_record_db
				->field('count(*) as partake_count,channelId')
				->where($map)
				->group('channelId')
				->order('channelId asc')
				->select();

			}
			foreach ($channel_data as $key => $value) {
				if($value['channelId']){
					$channel_name = $channel_list[$value['channelId']]; 
					$value['channel_name'] =  $channel_name? $channel_name:'';
					$visit_map['channelId'] = $value['channelId'];
					$visit_map['cid'] = $cid;
					$visit_map['activityId'] = $activity_id;
					$visit_map['deleted'] = 0;
					$value['visit_count'] = $miactivity_visit_db->where($visit_map)->group('userId')->count();
				}else{
					$value['channelId'] = 0;
					$value['channel_name'] = '';
					$value['visit_count'] = 0;
				}

				if(!$value['partake_count']){
					$value['partake_count'] = 0;
				}
				$channel_data[$key] = $value;
			}
			$list = $channel_data;
			break;
			case 'day':
			if($returnJson==true){
				$date_data = $miluckydraw_record_db
				->field("count(*) as partake_count,DATE_FORMAT(createTime,'%Y-%m-%d') as date_day")
				->where($map)
				->group('date_day')
				->order('date_day asc')
				->limit($start,$limit)
				->select();
				$sql = "select count(*) as count from (SELECT DATE_FORMAT(createTime,'%Y-%m-%d') as date_day    FROM `wx_miluckydraw_record` WHERE ( `cid` = $cid ) AND ( `activityId` = $activity_id )  GROUP BY date_day ) t ;";
				$count_search = M()->query($sql);
				$count = $count_search[0]['count'];

			}else{
				$date_data = $miluckydraw_record_db
				->field("count(*) as partake_count, DATE_FORMAT(createTime,'%Y-%m-%d') as date_day")
				->where($map)
				->group('date_day')
				->order('date_day asc')

				->select();

			}
			foreach ($date_data as $key => $value) {
				$date_day = $value['date_day'];
				$visit_map['1'] = array('exp',"DATE_FORMAT(createTime,'%Y-%m-%d')=$date_day") ;
				$visit_map['cid'] = $cid;
				$visit_map['activityId'] = $activity_id;
				$visit_map['deleted'] = 0;
				$value['visit_count'] = $miactivity_visit_db->where($visit_map)->group('userId')->count();

				
				if(!$value['partake_count']){
					$value['partake_count'] = 0;
				}
				$date_data[$key] = $value;
			}
			$list = $date_data;
			break;
			

		}



		$summary_data['channel_data'] = $channel_data;
		$summary_data['date_data'] = $date_data;
		if($list){
			Session::switchCustomer($cid);
			if($returnJson==true){
				Output::instance()->objArray($list, $count);
			}else{
				return $summary_data;
			}

		}else{
			Output::instance()->resultCode();
		}
	}

    /**
     * 晒照片活动数据导出
     */
    public function export($activity_id,$type="day"){
    	$result = array();
        $expTitle = '活动参与信息' ; //设置文件名
        $fileName = '活动参与信息' . date('Ymd'); //设置文件名


        Session::switchCustomer(0);
        $activity_name =  M('miactivity')->where('id='.$activity_id)->getField('activityname');

        switch ($type) {
        	case 'day':
        	$summary_data = $this->getDateChannelSummary($activity_id,$type,0,0,false);
        	$expCellName  = array(
        		array('date_day','日期'),
        		array('partake_count','参与人数'),
        		
        		array('visit_count','浏览人数'),
        		);
        	$expTableData = $summary_data['date_data'];
        	$fileName = $activity_name.'_按日期统计_' . date('Ymd');
        	break;
        	case 'channel':
        	$summary_data = $this->getDateChannelSummary($activity_id,$type,0,0,false);
        	$expCellName  = array(
        		array('channel_name','渠道'),
        		array('partake_count','参与人数'),
        		
        		array('visit_count','浏览人数'),
        		);
        	$expTableData = $summary_data['channel_data'];
        	$fileName = $activity_name.'_按渠道统计_' . date('Ymd');
        	break;
        	case 'partakeList':
        	$summary_data = $this->getPartakeList($activity_id,false,0,'id','asc',0,0,false);
        	foreach ($summary_data as $key => $value) {
        		if($value['item_type'] == 4){
        			$value['status'] = '未抽中';
        		}else{
        			if($value['gain_status'] == 0){
        				$value['status'] = '抽中未领取';
        			}else if($value['gain_status'] == 1){
        				if($value['prize_status'] == 0){
        					$value['status'] = '已经领取未发放';
        				}else{
        					$value['status'] = '已发放';
        				}
        			}
        		}
        		$summary_data[$key] = $value;
        	}
        	// echo json_encode($summary_data);
         //    exit;
        	$expCellName  = array(
        		array('id','序号'),
        		array('nickname','中奖用户'),
        		array('channel_name','渠道'),
        		array('info','奖项'),
        		array('createTime','时间'),
        		array('real_name','姓名'),
        		array('telephone','手机号码'),
        		array('id_card','身份证号码'),
        		array('status','状态'),
        		// array('headimgurl','头像'),
        		// array('nickname','昵称'),
        		);
        	$expTableData = $summary_data;
        	$fileName = $activity_name.'_参与记录_' . date('Ymd');
        	break;
        	case 'item':
        	$summary_data = $this->get_item_list($activity_id,false);
        	// foreach ($summary_data as $key => $value) {
        	// 	$summary_data[$key]['has_use_count'] = $value['has_use'].'/'.$value['count'];
        	// }
        	$expCellName  = array(
        		array('title','奖项'),
        		array('count','总数量'),
        		array('has_use','中奖数量'),
        		
        		// array('visit_count','浏览人数'),
        		);
        	$expTableData = $summary_data;
        	$fileName = $activity_name.'_按奖项统计_' . date('Ymd');
        	break;
        	case 'item_rate':
        	$summary_data = $this->get_item_list($activity_id,false);
        	$has_use_total = 0;
        	foreach ($summary_data as $key => $value) {
                $has_use_total +=$value['has_use'];
        		
        	}
        	foreach ($summary_data as $key => $value) {
        		if($has_use_total <= 0){
        			$item_rate = 0;
        		}else{
        			$item_rate = sprintf('%.2f',floatval($value['has_use'])/$has_use_total);
        		}
        		$value['item_rate'] = $item_rate;
        		$summary_data[$key] = $value;
        	}
        	$expCellName  = array(
        		array('title','奖项'),
        		
        		array('item_rate','占比'),
        		
        		// array('visit_count','浏览人数'),
        		);
        	$expTableData = $summary_data;
        	$fileName = $activity_name.'_按奖项统计_' . date('Ymd');
        	break;
        	default:

        	break;
        }
        $expTableDataTemp = array();
        foreach ($expTableData as $key => $value) {
        	$expTableDataTemp[] = $value;
        }

        if($expTableDataTemp){
        	Output::instance()->objArrayExcel($fileName,$expCellName,$expTableDataTemp);
        }



    }

 /*
    *获取活动参与记录
    */
 public function getPartakeList($activity_id,$keyword='',$channel_id=0,$order = 'id',$by='desc',$start = 0, $limit = 10,$returnJson=true,$status=0){
 	$retVal = Session::init();
 	if (!$retVal) {
 		Output::instance()->resultCode(code_access_denied);
 		return;
 	}
 	$cid = Session::$user["customerId"];
 	Session::switchCustomer(0);
 	$miactivity_visit_db = M("miactivity_visit");
 	$partake_db = M('miactivity_partake');
 	$miactivity_channel_db = M('miactivity_channel');
 	$miluckydraw_record_db = M("miluckydraw_record");
 	$map = array();
 	$map['c.activityId'] = $activity_id;

 	$map["c.cid"] = $cid;
 	if($keyword&&$keyword != ''){
 		$map['c.real_name|c.nickname|c.telephone'] = array(array('like','%'.$keyword.'%'),array('like','%'.$keyword.'%'),array('like','%'.$keyword.'%'),'_multi'=>true);
 	}

 	if($channel_id > 0){
 		$map['c.channelId'] = $channel_id;
 	}
 	switch ($status) {
 		case '1':
 			$map['c.item_type'] = 4;
 			break;
 			case '2':
 			$map['c.item_type'] = array('neq',4);
 			break;
 			case '3':
 			$map['c.gain_status'] = 1;
 			break;
 			case '4':
 			$map['c.item_type'] = array('neq',4);
 			$map['c.prize_status'] = 1;

 			break;
 	}
 	if($returnJson == true){
 		$list = $miluckydraw_record_db->alias('c')
 		->field('c.*')  
 		->where($map)
 		->distinct(true)
 		->order($order.' '.$by)
 		->limit($start.', '.$limit)
 		->select();
 	}else{
 		$list = $miluckydraw_record_db->alias('c')
 		->field('c.*')  
 		->where($map)
 		->distinct(true)
 		->order($order.' '.$by)
 		->select();
 	}


 	$channel_map = array();
 	$channel_map['cid'] = $cid;
 	$channel_map['deleted'] = 0;
 	$channel_list = $miactivity_channel_db->where($channel_map)->cache(true)->getField('id,name');

 	$visit_map = array();
 	foreach ($list as $key => $value) {
 		$value['channel_name'] = $channel_list[$value['channelId']];
 		$list[$key] = $value;
 	}

 	if ($list) {
 		if($returnJson == true){
 			$count =  $miluckydraw_record_db->alias('c')
 			->field('c.*')
 			->where($map)
 			->distinct(true)
 			->count();
 			Session::switchCustomer($cid);
 			Output::instance()->objArray($list,$count);
 		}else{
 			return $list;
 		}

 	} else {
 		Output::instance()->resultCode();
 	}
 }


} 